package fr.kraml;

import java.util.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.widget.ArrayAdapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class LoginFragment extends Fragment {

	// Messages reçus du service !
	//static final int MSG_ROOM_LIST = 20001;
	// Messenger pour la communication avec le service
	//Messenger mService = null;
	// Mon service est-il bindé ?
	boolean mIsBound;

	final Messenger mMessenger = new Messenger(new IncomingHandler());

	View mView;
	TextView tv;
	EditText username;
	EditText password;
	Spinner spinner_room_list;
	LoginFragmentListener mCallback;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		/*
		 * Intent intent = new Intent(getActivity(), KramlService.class);
		 * intent.putExtra("a", "login"); intent.putExtra("u", user.getText());
		 * intent.putExtra("p", pass.getText());
		 * getActivity().startService(intent);
		 */
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		mView = inflater.inflate(R.layout.login_fragment, container, false);

		doBindService();

		username = (EditText) mView.findViewById(R.id.loginUserName);
		password = (EditText) mView.findViewById(R.id.loginPassword);
		spinner_room_list = (Spinner) mView.findViewById(R.id.loginRoomList);
		Button b = (Button) mView.findViewById(R.id.loginButton);

		b.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/*mCallback.onLoginPressed(user.getText().toString(), pass
						.getText().toString());*/
				login();
			}
		});

		return mView;

	}

	public LoginFragment() {
		// TODO Auto-generated constructor stub
	}

	// Container Activity must implement this interface
	public interface LoginFragmentListener {
		public void onLoginPressed(String user, String pass, String roomname);
		public void majRoomListLoginFragment();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception
		try {
			mCallback = (LoginFragmentListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement LoginFragmentListener");
		}
	}

	/*
	 * public void setText(String txt) { tv.setText(txt); }
	 */

	/*
	 * public static PVFragment newInstance(String user) { PVFragment fragment =
	 * new PVFragment(); Bundle args = new Bundle(); args.putString("user",
	 * user); fragment.setArguments(args); return fragment; }
	 */

	void doBindService() {
		// Establish a connection with the service. We use an explicit
		// class name because there is no reason to be able to let other
		// applications replace our component.
		getActivity().getApplicationContext()
				.bindService(
						new Intent(LoginFragment.this.getActivity(),
								KramlService.class), mConnection,
						Context.BIND_AUTO_CREATE);
		mIsBound = true;

		// mCallbackText.setText("Binding.");
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// This is called when the connection with the service has been
			// established, giving us the service object we can use to
			// interact with the service. We are communicating with our
			// service through an IDL interface, so get a client-side
			// representation of that from the raw service object.

			/*mService = new Messenger(service);

			try {
				Message msg = Message.obtain(null, KramlService.MSG_MESSAGE);
				msg.replyTo = mMessenger;
				mService.send(msg);
			} catch (RemoteException e) {
				// In this case the service has crashed before we could even do
				// anything with it
			}*/

			// Get room list
			/*Message msg = Message.obtain(null, KramlService.MSG_ROOM_LIST);
			try {
				mService.send(msg);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			mCallback.majRoomListLoginFragment();

			// mService = new Messenger(service);
			// mCallbackText.setText("Attached.");

			// We want to monitor the service for as long as we are
			// connected to it.
			/*
			 * try { Message msg = Message.obtain(null, 0); msg.replyTo =
			 * mMessenger; mService.send(msg);
			 * 
			 * // Give it some value as an example. msg = Message.obtain(null,
			 * 1, this.hashCode(), 0); mService.send(msg); } catch
			 * (RemoteException e) { // In this case the service has crashed
			 * before we could even // do anything with it; we can count on soon
			 * being // disconnected (and then reconnected if it can be
			 * restarted) // so there is no need to do anything here. }
			 */

			// As part of the sample, tell the user what happened.
			Toast.makeText(LoginFragment.this.getActivity(), "connected",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onServiceDisconnected(ComponentName className) {
			// This is called when the connection with the service has been
			// unexpectedly disconnected -- that is, its process crashed.
			//mService = null;
			// mCallbackText.setText("Disconnected.");

			// As part of the sample, tell the user what happened.
			Toast.makeText(LoginFragment.this.getActivity(), "Disconnected",
					Toast.LENGTH_SHORT).show();
		}
	};

	@SuppressLint("HandlerLeak")
	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			/*switch (msg.what) {
			case MSG_ROOM_LIST:
				String room_list = msg.getData().getString("room_list");

				Log.i("LoginFragment", "RoomListReceived : " + room_list);

				// MAJ dropDownList
				// spinner_room_list
				List<String> list = new ArrayList<String>();
				try {
					JSONArray rooms = new JSONArray(room_list);
					for (int i = 0; i < rooms.length(); i++) {
						JSONObject item = rooms.getJSONObject(i);
						list.add(item.getString("room_name"));
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
						getActivity(), R.layout.simple_line, list);
				dataAdapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

				spinner_room_list.setAdapter(dataAdapter);

				break;
			default:
				super.handleMessage(msg);
			}*/
		}
	}
	
	public void login() {
		/*username.getText().toString();
		Bundle b = new Bundle();
		b.putString("user", username.getText().toString());
		b.putString("pass", password.getText().toString());
		b.putString("room", (String) spinner_room_list.getSelectedItem());
		Message msg = Message.obtain(null, KramlService.MSG_LOGIN);
		msg.setData(b);
		try {
			mService.send(msg);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		String room = "Nouveaux Venus";
		if (spinner_room_list.getSelectedItem() != null) room = spinner_room_list.getSelectedItem().toString();
		mCallback.onLoginPressed(username.getText().toString(), password.getText().toString(), room);
	}
	
	public void majRoomList(String json) {
		Log.i("LoginFragment", "RoomListReceived : " + json);

		// MAJ dropDownList
		// spinner_room_list
		List<String> list = new ArrayList<String>();
		try {
			JSONArray rooms = new JSONArray(json);
			for (int i = 0; i < rooms.length(); i++) {
				JSONObject item = rooms.getJSONObject(i);
				list.add(item.getString("room_name"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
				getActivity(), R.layout.simple_line, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinner_room_list.setAdapter(dataAdapter);

	}
	
}
